import 'package:flutter/material.dart';
import 'package:flutter_module/beans/data_layer_bean.dart';
import 'package:flutter_module/beans/data_layer_item_bean.dart';
import 'package:flutter_module/beans/data_layer_item_selection_bean.dart';
import 'package:flutter_module/beans/element_bean.dart';
import 'package:flutter_module/beans/element_style_bean.dart';
import 'package:flutter_module/beans/project_bean.dart';
import 'package:flutter_module/data/data_manager.dart';
import 'package:flutter_module/map/ni_types.dart';
import 'package:flutter_module/system/log_util.dart';
import 'package:flutter_module/data/ni_data_controller.dart';
import 'package:fluttertoast/fluttertoast.dart';

///用来处理图层模板的新增和编辑
class LayerEditViewModel with ChangeNotifier {
  ///当前选中的项目
  Project? curSelectProject;

  ///当前正在编辑的项目
  Project? curEditProject;

  ///当前正在编辑的layer
  DataLayer curLayer = DataLayer(itemList: []);

  ///当前正在编辑的属性
  DataLayerItem curItem = DataLayerItem(title: "");

  ///在更新属性的时候，先保留原来的属性，用来恢复修改前的数据
  DataLayerItem? tempItem;

  ///项目列表
  List<Project> projectList = [];

  ///当前的数据图层集合
  List<DataLayer> dataLayerList = [];

  ///是否是新
  bool isNewProject = false;

  ///是否新增图层，还是更新图层
  bool isNewLayer = true;

  ///是否是新增属性
  bool isNewItem = false;

  ///选择项列表
  List<SelectionBean> selectionList = [];

  ///渲染样式
  ElementStyle? elementStyle;


  ///获取所有数据图层
  Future getDataLayerList() async {
    dataLayerList =
    await DataManager.instance.dataController.queryDataLayerList();
    projectList =
    await DataManager.instance.dataController.queryDataProjectList();
    notifyListeners();
  }


  ///销毁当前正在编辑的项目
  void disposeEditProject() {
    curEditProject = null;
  }

  ///设置当前要编辑的项目，[isNew] 是否是新增还是修改
  void setEditProject(Project project, bool isNew) {
    isNewProject = isNew;
    curEditProject = project;
  }

  ///保存项目
  Future<bool> saveEditProject() async {
    if (curEditProject != null) {
      var value = await DataManager.instance.dataController
          .saveProject(curEditProject!);
      if (value) {
        if (isNewProject) {
          projectList.add(curEditProject!);
        } else {
          notifyListeners();
        }
        return true;
      }
    }
    return false;
  }

  @override
  void dispose() {
    curSelectProject = null;
    curEditProject = null;
    LogUtil.instance.printf("我被销毁了");
    super.dispose();
  }

  void setCurProject(Project project) {
    curSelectProject = project;
    curLayer.projectId = project.uuid;
    notifyListeners();
  }

  Future getProjectList() async {
    projectList =
        await DataManager.instance.dataController.queryDataProjectList();
  }

  ///检查是不是已经有了一个主字段用来在地图上渲染
  bool isHisMainName() {
    if (curLayer.itemList.isNotEmpty) {
      for (var item in curLayer.itemList) {
        if (item.isMainName) {
          return true;
        }
      }
    }
    return false;
  }

  void notifyListener() {
    notifyListeners();
  }
}

///图层基础属性操作部分，不包括项目和具体的属性
extension ProjectControl on LayerEditViewModel {
  ///设置当前要编辑的图层，不传值就是新建，传值就是更新
  void initProject(Project? project) {
    if (project != null) {
      curSelectProject = project;
    }
  }
  ///设置当前要编辑的图层，不传值就是新建，传值就是更新
  void initLayer({DataLayer? dataLayer}) {
    if (dataLayer != null) {
      isNewLayer = false;
      curLayer = dataLayer;
      if(dataLayer.style != ""){
        elementStyle = ElementStyle.fromJson(dataLayer.style);
      }else{
        elementStyle = ElementStyle();
      }

    } else {
      isNewLayer = true;
      elementStyle = ElementStyle();
      curLayer.itemList
          .add(DataLayerItem(title: "名称", nullable: false, isMainName: true));
    }
  }

  ///保存图层数据
  Future<bool> saveLayer() async {
    if (curLayer.itemList.isEmpty) {
      Fluttertoast.showToast(msg: "还没有添加任何属性");
      return false;
    }
    for (var i = 0; i < curLayer.itemList.length; i++) {
      curLayer.itemList[i].key = "Key$i";
    }
    elementStyle ??= ElementStyle();
    curLayer.style = elementStyle!.toJson();
    return await DataManager.instance.dataController.createDataLayer(curLayer);
  }

  ///设置图层数据类型
  void setLayerGeometryType(var value) {
    if (value is GeometryType) {
      curLayer.geometryType = value;
      notifyListener();
    }
  }
}

///图层具体的某条属性操作部分
extension ItemControl on LayerEditViewModel {
  ///初始化当前要编辑的图层属性，不传值视为新增
  void initLayerItem({DataLayerItem? item}) {
    if (item != null) {
      isNewItem = false;
      tempItem = item;
      curItem = item.copy();
    } else {
      isNewItem = true;
      curItem = DataLayerItem(title: "");
    }
  }

  ///设置图层属性的类型
  void setLayerItemType(DataLayerItemType type) {
    curItem.type = type;
    notifyListener();
  }

  ///保存属性
  bool saveItem() {
    if (curItem.title.isEmpty) {
      Fluttertoast.showToast(msg: "请输入属性名称");
      return false;
    }

    switch (curItem.type) {
      case DataLayerItemType.dataLayerItemTypeInput:
        curItem.selectOptions = null;
        break;
      case DataLayerItemType.dataLayerItemTypeSingleSelection:
        List<String> names = [];
        List<String> values = [];
        for (SelectionBean bean in selectionList) {
          if (bean.name.isEmpty) {
            Fluttertoast.showToast(msg: "请填写选项名称");
            return false;
          }
          if (bean.value.isEmpty) {
            Fluttertoast.showToast(msg: "请填写选项隐藏值");
            return false;
          }
          names.add(bean.name);
          values.add(bean.value);
        }
        int lName = names.length;
        int lValue = names.length;
        if (lName == 0) {
          Fluttertoast.showToast(msg: "还没有添加任何选项");
          return false;
        }
        if (names.toSet().toList().length < lName) {
          Fluttertoast.showToast(msg: "选项名称有重复");
          return false;
        }
        if (values.toSet().toList().length < lValue) {
          Fluttertoast.showToast(msg: "选项默认值有重复");
          return false;
        }

        ///默认选择类型的属性要必选，不能为主键和主显示名称
        curItem.nullable = false;
        curItem.primaryKey = false;
        curItem.isMainName = false;
        curItem.selectOptions = List.from(selectionList);
        break;
    }
    if (isNewItem) {
      curLayer.itemList.add(curItem);
    } else if (tempItem != null) {
      tempItem!.copyValues(curItem);
    }
    notifyListener();
    return true;
  }

  ///设置这条属性是必填项还是非必填项
  void setItemNullable(bool nullable) {
    curItem.nullable = nullable;
    notifyListener();
  }

  ///设置这条属性是必填项还是非必填项
  void setItemMainName(bool isMainName) {
    if (!isMainName) {
      for (var element in curLayer.itemList) {
        element.isMainName = false;
      }
    }
    curItem.isMainName = isMainName;
    notifyListener();
  }
}

///用来处理单选属性的详细内容
extension SingleSelectionItemControl on LayerEditViewModel {
  void initSingleSelectionItem({List<dynamic>? list}) {
    if (list != null) {
      selectionList = List.from(list);
    } else {
      selectionList = [];
    }
  }
}
///渲染样式
extension StyleControl on LayerEditViewModel{
  void setStyleRule(int rule){
    if(elementStyle != null){
      elementStyle!.rule = rule;
      notifyListener();
    }
  }
}